// pages/home/index.js
// pages/home/
const api = require("../../request/api")
const request = require("../../request/request")
const util = require("../../utils/util")
const App = getApp();
// const cailanzi64 = require("../../images/cailanzi64")

let firstsrc = 'http://wxsnsdy.tc.qq.com/105/20210/snsdyvideodownload?filekey=30280201010421301f0201690402534804102ca905ce620b1241b726bc41dcff44e00204012882540400&bizid=1023&hy=SH&fileparam=302c020101042530230204136ffd93020457e3c4ff02024ef202031e8d7f02030f42400204045a320a0201000400'
let songvideo = 'http://img.qian.gzzsu.com/shop/qiankanghui/doctor-img/song.mp4'
let chengvideo = 'http://img.qian.gzzsu.com/shop/qiankanghui/doctor-img/cheng.mp4'
// let testvideo = 'http://img.qian.gzzsu.com/shop/qiankanghui/home-img/testvideo2.mp4'

let videos = [songvideo, chengvideo]

Page({

    /**
     * 页面的初始数据
     */

    inputValue: '',

    data: {
        barHeight: App.globalData.paddingTop,
        styledata: {
            "bg_color": "white",
            "color": "#000",
            "name": "品牌首页",
            "leftflag": true,
            "homeflag": true,
        },
        titleArr: ["品牌首页", "品牌选品", "品牌健康"],
        bannerSwiper_list: [],
        goodSwiper_list: [],
        autoBanners: false,
        autoGoods: false,

        swiper_list_bottom: [
            { src: "http://img.qian.gzzsu.com/shop/qiankanghui/home-img/QJinvite.png" },
        ],
        category_list: [],
        uid: '',
        page: 1,
        page_size: 8,
        good_list: [],
        current_index: 0,
        if_follow: false,
        middle_list: '',
        more_list: [],

        promotion_list: [],
        brand_list: [],


        options: {},
        // 推广商品的轮播启动标识，为了和广告的动画不同步
        startgood: false,

        // 品牌详情
        brandDetail: {},
        // 品牌商品列表
        brandgoodslist: [],

        // 刷新标识
        ispullrefresh: false,

        // 品牌首页距离顶部触发事件的距离
        topindex: 0,

        // 回到顶部图标
        ShowTop: false,

        // 当前导航栏索引
        currentnum: 0,


        // 选品
        category_list: [],
        good_list2: [],
        uid: '',
        page2: 1,
        page_size2: 6,
        current_index2: 0,
        default_seacrhing_list: [{
            name: '妇科千金片'
        }, {
            name: '私处洗液'
        }, {
            name: '加味逍遥丸'
        }],

        noMore2: false,

        type: '',


        // 健康
        page3: 1,
        page_size3: 8,
        count: '',
        article_list: [],
        current_index3: 0,
        swiper_list: [],
        noMore3: false,

        src: '',
        showflag: 'block',
        doctorindex: 0
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: async function (options) {
        // 只有扫码进入品牌首页，才会携带id参数，将其设置为全局变量
        if (options.id) { App.globalData.brandId = options.id }
        // 获取品牌id,单纯保存到this对象上
        this.brand_id = App.globalData.brandId

        // 倍健视频路径特殊处理，后续应该接口增加字段保存
        if (this.brand_id == 14) {
            this.setData({
                src: videos[1],
                doctorindex: 1
            })
        } else {
            this.setData({
                src: videos[0],
                doctorindex: 0
            })
        }

        this.init_data()
        const timer1 = setTimeout(() => {
            this.setData({
                startgood: true
            })
            clearTimeout(timer1)
        }, 1000);

        // share 分享商品或资讯的跳转路径 如果有即从首页跳转，以便返回可以回到首页
        let { share } = options
        if (share) {
            wx.navigateTo({
                url: `${share}?sid=${options.sid}&id=${options.id}`,
            })
        }

        // 目前用不上
        // this.get_category_list()
        // this.get_goods_list()
        // this.get_middle_list()
        // this.get_promotion_list()

        // 首页
        await this.get_more_list()
        await this.get_brand_list()
        await this.getBrandSwiper()

        await this.getbrandDetail()
        // await this.getbrandGoods()

        // 选品页
        this.get_category_list()

        // 健康页面
        this.getSwiper()
        this.get_article_list2()
    },

    init_data() {
        this.setData({
            uid: App.globalData.uid || util.getAppValue('userInfo').uid,
        })

    },

    videoEnd() {
        // console.log(e, '结束播放了');
        this.closebox()
    },

    // 跳转医师简介
    goto_doctor(e) {
        // let imgstr = e.currentTarget.dataset.docimg
        // let doctorindex = 0
        // switch (imgstr) {
        //     case 'http://img.qian.gzzsu.com/shop/qiankanghui/home-img/doctor.png':
        //         doctorindex = 0 // 宋主任
        //         break;
        //     case 'http://img.qian.gzzsu.com/shop/qiankanghui/home-img/BJdoctor.png':
        //         doctorindex = 1 // 陈总
        //         break;
        //     default:
        //         doctorindex = 0
        //         break;
        // }
        // console.log(doctorindex);
        let doctorindex = this.data.doctorindex
        wx.navigateTo({
            url: `/brand/doctor/doctor?index=${doctorindex}`,
            success: (result) => {

            },
            fail: () => { },
            complete: () => { }
        });
    },

    // 处理swiper高度自适应
    goheight: function (e) {
        var width = wx.getSystemInfoSync().windowWidth
        //获取可使用窗口宽度
        var imgheight = e.detail.height
        //获取图片实际高度
        // var imgwidth = e.detail.width
        //获取图片实际宽度
        // var height = width * imgheight / imgwidth + "px"
        //计算等比swiper高度
        // console.log(imgheight);
        this.setData({
            swiperheight: imgheight / 2
        })
    },

    // 点击底部栏滑动切换
    changetaps(e) {
        this.setData({
            currentnum: e.detail,
            'styledata.name': this.data.titleArr[e.detail]
        })
    },

    // 滑动切换
    changing_swiper_item(e) {
        this.setData({
            currentnum: e.detail.current,
            'styledata.name': this.data.titleArr[e.detail.current]
        })
    },

    // 获取品牌详情
    async getbrandDetail() {
        let res = await request.post(api.BrandDeatail, { id: this.brand_id })
        this.setData({
            brandDetail: res
        })
        // console.log(res);
    },

    // 获取品牌商品列表
    async getbrandGoods() {
        let params = {
            id: this.brand_id,
            page: this.data.page,
            limit: this.data.page_size
        }
        let res = await request.post(api.BrandIndex, params)
        this.setData({
            brandgoodslist: res.goods
        })
        console.log(res);
    },

    getBrandSwiper() {
        this.setData({
            bannerSwiper_list: [],
            goodSwiper_list: [],
            autoBanners: false,
            autoGoods: false,
        })

        let params = {
            id: this.brand_id,
            page: 1,
            limit: 1
        };

        request.post(api.BrandIndex, params).then(res => {
            this.setData({
                bannerSwiper_list: res.swiperBanners.list,
                goodSwiper_list: res.swiperGoods.list,
                autoBanners: res.swiperBanners.autopaly,
                autoGoods: res.swiperGoods.autopaly,
            })
        })
    },

    // 推广商品列表
    get_promotion_list() {
        let params = {
            page: 1,
            pageSize: 2,
            // uid: this.data.uid,
            type: 'default'

        }
        request.post(api.goods_more, params).then(res => {
            this.setData({
                promotion_list: res
            })
        })
    },

    // 品牌商品列表
    get_brand_list() {
        let params = {
            id: this.brand_id,
            page: 1,
            limit: 6,
            // uid: this.data.uid,
            type: 'default'
        }
        request.post(api.BrandIndex, params).then(res => {
            this.setData({
                brand_list: res.goods
            })
        })
    },


    get_new_goods_list() {
        let params = {
            page: this.data.page,
            pageSize: this.data.page_size,
            // uid: this.data.uid,
            type: 'default'

        }
        let old_list = this.data.good_list
        request.post(api.goods_more, params).then(res => {
            if (res.length != 0) {
                let new_list = old_list.concat(res)
                this.setData({
                    good_list: new_list
                })
            }
            else {
                this.setData({
                    noMoreData: true
                });
                util.showToast('暂无更多商品了');
            }
        })
    },
    get_goods_list() {
        let params = {
            page: this.data.page,
            pageSize: this.data.page_size,
            // uid: this.data.uid,
            type: 'default'

        }
        request.post(api.goods_more, params).then(res => {
            this.setData({
                good_list: res
            })
        })
    },
    get_middle_list() {
        let params = {
            page: 1,
            pageSize: 6,
            // uid: this.data.uid,
            type: 'default'
        }
        request.post(api.goods_more, params).then(res => {
            this.setData({
                middle_list: res
            })
        })
    },

    get_more_list() {
        let params = {
            brand_id: this.brand_id,
            page: this.data.page,
            limit: this.data.page_size,
            // type: 'default',
            is_selected: 1
        }
        request.post(api.goods_more, params).then(res => {
            // res = res.goods
            if (res.length == 0) {
                this.setData({
                    noMore: true
                })
                util.showToast('暂无更多相关商品')
                return
            }
            for (var i = 0; i < res.length; i++) {
                let mx = parseInt(Math.random() * 10) / 10
                let youhui = res[i].sell_price * (mx * 0.04 + 0.08)
                res[i].youhui = youhui.toFixed(2)
            }

            // 如果是刷新清空原数组
            if (this.isReload) {
                this.setData({
                    more_list: []
                })
                this.isReload = false
                util.showToast('刷新成功')
            }

            let list = this.data.more_list
            let new_list = list.concat(res)
            this.setData({
                more_list: new_list
            })
        })
    },

    // 轮播图设置当前小点 用于展示
    indicator_change(event) {
        this.setData({
            current_index: event.detail.current
        })
    },

    // 跳转快速选品页面
    category_navigation(e) {
        let index = e.currentTarget.dataset.index
        let url = '/pages/home/classify?index=' + index
        wx.reLaunch({
            url,
        })
    },

    // 团购跳转 16号临时更改
    go_group_buying() {
        // let url = '/pages/group_buying/group_buying'
        // wx.navigateTo({
        //     url
        // })
        console.log('ooopdddee');
        wx.showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline']
        })
    },

    // 查看商品详情
    go_detail(e) {
        let id = e.detail.currentTarget.dataset.id
        wx.navigateTo({
            url: '/pages/good/detail?id=' + id,
        })
    },

    go_good_detail(e) {
        let id = e.currentTarget.dataset.id
        if (!id) {
            util.showToast('所选商品暂无记录')
            return
        }
        wx.navigateTo({
            url: '/pages/good/detail?id=' + id,
        })
    },

    // 商品列表组件点击触发的回调
    go_detail_from_component(e) {
        let id = e.detail.currentTarget.dataset.id
        if (!id) {
            util.showToast('所选商品暂无记录')
            return
        }
        wx.navigateTo({
            url: '/pages/good/detail?id=' + id,
        })
    },

    // 商品列表组件点击加入购物车
    async cart_add(e) {
        if (!this.data.uid) {
            util.showToast('请登录后再添加购物车哦')
            return
        }
        let id = e.detail.currentTarget.dataset.id
        let goodDetail = await request.post(api.goods_details, { id })
        if (goodDetail.store_nums <= 0) {
            wx.showToast({
                title: '该商品暂无库存，请挑选别的心仪商品吧',
                icon: 'none',
                duration: 2000
            });
            return
        }

        // 筛选最低价格规格id，默认选最低规格
        let temArr = []
        goodDetail.products_array.forEach(item => {
            temArr.push(item.sell_price)
        });
        let lowestProPrice = Math.min(...temArr)
        let lowestIndex = temArr.indexOf(lowestProPrice)
        let skuid = goodDetail.products_array[lowestIndex].id
        // console.log('skuid', skuid);

        let params = {
            goods_id: id,
            uid: this.data.uid,
            goods_sku_id: skuid
        }
        let res = await request.post(api.cart_add, params)
        if (res) {
            let cartRes = await request.post(api.cart_list, { uid: this.data.uid })
            // console.log(cartRes);
            App.globalData.cartnum = cartRes.total_goods_nums
        }
        util.showToast("已加入购物车")

    },

    // 搜索栏跳转
    go_search() {
        App.globalData.tabindex = 1
        wx.redirectTo({
            url: '/brand/brand/classify',
        })
    },

    // 菜篮子跳转小程序
    go_cailanzi_program() {
        wx.navigateToMiniProgram({
            appId: 'wxb1f5b7f152b1858d',
        })
    },

    // 跳转推广页面
    go_promotion() {
        let url = '/pages/promotion/promotion'
        wx.navigateTo({
            url
        })
    },

    go_welfare() {
        let url = '/pages/welfare/welfare'
        wx.navigateTo({
            url,
        })
    },

    go_brand() {
        let url = '/pages/brand/brand'
        wx.navigateTo({
            url,
        })
    },

    go_vip() {
        let url = '/vip/vip'
        wx.navigateTo({
            url,
        })
    },

    go_zone(e) {
        let url = "/pages/home/zone?index=" + e.currentTarget.dataset.index
        wx.navigateTo({
            url,
        })
    },

    go_contact() {

    },

    // 获取滑动位置
    indexTotop: function (e) {
        // wx.getSystemInfoSync().windowHeight 系统手机窗口高度
        // 当页面滑动距离大于一屏的高度时显示回到顶部控件
        // console.log(e.detail.scrollTop);
        this.setData({
            ShowTop: e.detail.scrollTop > wx.getSystemInfoSync().windowHeight ? true : false
        });
    },

    // 点击回到顶部
    clickToTop() {
        this.setData({
            topindex: 0
        })
    },

    // 上拉加载更多
    loadmore() {
        if (!this.data.noMore) {
            this.setData({
                page: ++this.data.page
            })
            this.get_more_list();
        }
    },

    // 下拉刷新
    pullRefresh(e) {
        setTimeout(async () => {
            this.setData({
                noMore: false,
                page: 1,
                more_list: [],
                brand_list: []
            })
            await this.get_more_list()
            await this.get_brand_list()
            await this.getBrandSwiper()
            this.setData({
                ispullrefresh: false
            })
        }, 1800);
    },





    // 选品页面js
    go_search() {
        wx.navigateTo({
            url: '/pages/good/search',
        })
    },

    // 请求商品分类
    get_category_list(index = 0) {
        // console.log('this.brand_id', this.brand_id);
        let params = {
            page: 1,
            limit: 15
        }

        request.post(api.category_list, params).then(res => {
            // res.reverse()
            // console.log('res', res);
            let newlist = [{
                name: '全部',
                id: '',
                visibility: 1
            }]
            newlist.push(...res)
            let type = newlist[index].id
            this.setData({
                category_list: newlist,
                type

            })
            this.get_good_list()
        })
    },

    get_good_list() {
        let params = {
            page: this.data.page2,
            limit: this.data.page_size2,
            type: this.data.type,
            brand_id: this.brand_id == -1 ? '' : this.brand_id
        }
        let list = this.data.good_list2
        //  goods_list接口拿到的是redis缓存内容，查询用goodssearch
        request.post(api.goods_search, params).then(res => {
            if (res.length == 0) {
                this.setData({
                    noMore2: true
                })
                util.showToast('暂无更多相关商品')
                return
            }
            for (var i = 0; i < res.length; i++) {
                let mx = parseInt(Math.random() * 10) / 10
                let youhui = res[i].sell_price * (mx * 0.04 + 0.08)
                res[i].youhui = youhui.toFixed(2)
            }
            let new_list = list.concat(res)
            this.setData({
                good_list2: new_list
            })
        })
    },

    // 切换商品分类
    choosing_category(e) {
        let current_index2 = e.currentTarget.dataset.index
        let type = e.currentTarget.dataset.cate_id
        this.setData({
            current_index2,
            type,
            page2: 1,
            noMore2: false,
            good_list2: []
        })
        this.get_good_list()
    },

    loadmore2() {
        if (!this.data.noMore2) {
            this.setData({
                page2: ++this.data.page2
            })
            this.get_good_list()
        }
    },

    // 下拉刷新
    pullRefresh2() {
        setTimeout(async () => {
            this.setData({
                noMore2: false,
                page2: 1,
                category_list: [],
                good_list2: []
            })
            await this.get_category_list(this.data.current_index2)
            this.setData({
                classifyrefresh: false
            })
        }, 1800);
    },

    classifyTotop() { },


    // 健康页面js
    getSwiper() {
        let params = {
            type: 'articles'
        };

        //let that = this
        request.post(api.getSwiper, params).then(res => {
            this.setData({
                swiper_list: res.reverse()
            })
            // console.log(this.data.swiper_list)
        })

    },
    // indicator_change(event) {
    //     this.setData({
    //         current_index3: event.detail.current
    //     })
    // },
    // 切换轮播暂停视频播放
    indicator_change22(event) {
        // console.log('66666', event);
        // 轮播总长度
        let length = this.data.swiper_list.length
        let newIndex = event.detail.current
        let lastIndex, nextIndex

        // 将正在展示的轮播index，左右视频暂停
        if (newIndex == 0) {
            lastIndex = length - 1
            nextIndex = 1
        } else if (newIndex == length - 1) {
            lastIndex = length - 2
            nextIndex = 0
        } else {
            lastIndex = newIndex - 1
            nextIndex = newIndex + 1
        }

        // this.videoContext = wx.createVideoContext(`myVideo${newIndex}`)
        this.LvideoContext = wx.createVideoContext(`myVideo${lastIndex}`)
        this.NvideoContext = wx.createVideoContext(`myVideo${nextIndex}`)

        this.LvideoContext.pause()
        this.NvideoContext.pause()

    },
    go_article_detail(e) {
        let id = e.currentTarget.dataset.id
        wx.navigateTo({
            url: '/pages/health/health_detail?id=' + id,
        })
    },
    go_swiper_detail(e) {
        let id = e.currentTarget.dataset.url
        wx.navigateTo({
            url: '/pages/health/health_detail?id=' + id,
        })
    },

    // 处理分页器得点击跳转
    handlejump(e) {
        let page = e.detail.currentTarget.dataset.page
        this.setData({
            page3: page
        })
        this.get_article_list2()
        // console.log('处理分页器得点击跳转', e);
        // console.log(page);
    },

    // 使用分页器方式的文章请求方法
    async get_article_list2() {
        let params = {
            page: this.data.page3,
            limit: this.data.page_size3
        }
        let res = await request.postall(api.articlelist, params)
        // console.log(res);
        res.data.forEach(item => {
            let readnum = parseInt(Math.random() * 400) + 700
            let sharenum = parseInt(Math.random() * 100) + 100
            item.readnum = readnum
            item.sharenum = sharenum
        });

        this.setData({
            article_list: res.data,
            count: res.count
        })
    },

    async get_article_list() {
        let params = {
            // brand_id: this.brand_id,
            page: this.data.page3,
            limit: this.data.page_size3
        }
        let res = await request.post(api.articlelist, params)
        if (res.length == 0) {
            this.setData({
                noMore3: true
            })
            util.showToast('无更多内容')
            return
        }
        res.forEach(item => {
            let readnum = parseInt(Math.random() * 400) + 700
            let sharenum = parseInt(Math.random() * 100) + 100
            item.readnum = readnum
            item.sharenum = sharenum
        });
        let list = this.data.article_list
        let new_list = list.concat(res)
        this.setData({
            article_list: new_list
        })
    },

    // 健康资讯下拉刷新
    pullRefresh3() {
        setTimeout(() => {
            this.setData({
                page3: 1,
                article_list: [],
                noMore3: false
            })
            this.getSwiper()
            this.get_article_list2()
            this.setData({
                healthrefresh: false
            })
        }, 1800);
    },

    // 上拉加载
    // loadmore3() {
    //     if (!this.data.noMore3) {
    //         this.setData({
    //             page3: ++this.data.page3,
    //         })
    //         this.get_article_list();
    //     }
    // },

    healthTotop() { },


    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        // 获取视频组件对象
        this.videoContext = wx.createVideoContext('myVideo')
    },

    closebox() {
        this.videoContext.stop()
        this.setData({
            showflag: 'none'
        })
    },

    jumpdoctor(e) {
        // this.videoContext.stop()
        this.goto_doctor(e)
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        // 获取uid
        this.init_data()
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    },

    // 分享到朋友圈
    onShareTimeline() {

    },

    // 上拉到底部触发商品加载
    onReachBottom: function () {
    },
})